package com.roubsite.admin.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.roubsite.admin.dao.user.IUserDao;
import com.roubsite.admin.dao.user.UserDao;
import com.roubsite.admin.utils.TimeStampUtils;
import com.roubsite.database.annotation.Dao;
import com.roubsite.security.securityInfo.RSSecurityBaseUserInfo;
import com.roubsite.security.utils.RSPasswordUtil;
import com.roubsite.security.utils.RSSecurityUtils;
import com.roubsite.sso.utils.Base64Utils;
import com.roubsite.utils.JsonUtils;
import com.roubsite.utils.StringUtils;
import com.roubsite.web.action.RSAction;

@SuppressWarnings("rawtypes")
public class LoginAction extends RSAction {
	@Dao(impl = UserDao.class, dataSource = "dataSource")
	IUserDao userDao;

	@Override
	public void execute() throws Exception {
		String retUrl = (String) this.s("retUrl");
		if (StringUtils.isEmpty(retUrl)) {
			retUrl = "";
		}

		this.assign("reUrl", retUrl);
		this.getSession().setAttribute("reUrl", request.getContextPath());
		this.display("login.html");
	}

	/**
	 * 登陆方法（1：登陆成功。-2：密码错误。-1:没有该用户。-3:验证码错误。-4用户注销。-5用户锁定。）
	 * 
	 * @throws Exception
	 */
	public void doLogin() throws Exception {
		RSPasswordUtil passwordUtils = new RSPasswordUtil();
		int ret = 0;
		String username = (String) this.$_P("username");
		String pwd = (String) this.$_P("pwd");
		pwd = new String(Base64Utils.decode(pwd));
		String verifyImgCode = (String) this.$_P("verifyImg");
		String vvv = "";
		// 解锁时间
		String expTime = "";
		String rexpTime = "";
		// 当前时间
		String nowTime = StringUtils.getUnixDate();
		long nTime = Long.parseLong(nowTime);
		String logMsg = "";
		if (StringUtils.isNotEmptyObject(this.s("verifyImg"))) {
			vvv = (String) this.s("verifyImg");
		}
		vvv = vvv.toLowerCase();
		long startTime = 0;
		if (StringUtils.isNotEmptyObject(this.s("verifyImgTime"))) {
			try {
				startTime = Long.parseLong((String) this.s("verifyImgTime"));
			} catch (Exception e) {
			}
		}
		long endTime = Long.parseLong(StringUtils.getUnixDate());
		if ((endTime - startTime) > 300000) {// 两个时间戳是否相差5分钟
			ret = -10;
			logMsg = "验证码超时";
		} else {
			if (!verifyImgCode.toLowerCase().equals(vvv) || StringUtils.isEmpty(vvv)) {
				ret = -3;// 验证码错误
				logMsg = "验证码错误";
			} else {
				Map map = userDao.getUserInfo(username);

				if (null != map) {
					String status = (String) map.get("USER_STATUS");
					String passwd = (String) map.get("USER_PASSWORD");
					boolean ifStatus = false;
					if (status.equals("-1")) {
						expTime = (String) map.get("EXPIRED_TIME");
						long exTime = Long.parseLong(expTime);

						if (exTime <= nTime) {
							// 修改用户状态
							String userStatus = "1";
							ifStatus = true;
							userDao.upStatusByName(username, userStatus);
						} else {
							if (passwordUtils.matches(pwd, passwd)) {
								rexpTime = TimeStampUtils.stampTotimeComplete(Long.parseLong(expTime));
								ret = -5;// 用户锁定
								logMsg = "用户锁定";
							} else {
								ret = -2;
								logMsg = "密码错误";
							}
						}

					} else if (status.equals("0")) {
						ret = -4;// 用户注销
						logMsg = "用户已注销";
					} else if (status.equals("1")) {
						ifStatus = true;
					}
					if (ifStatus) {
						if (passwordUtils.matches(pwd, passwd)) {
							// 登陆成功
							RSSecurityBaseUserInfo userInfo = new RSSecurityBaseUserInfo();
							// 用户信息
							userInfo.setUid((String) map.get("USER_ID"));
							userInfo.setUserName(username);
							userInfo.setUserStatus((String) map.get("USER_STATUS"));
							// 用户组织信息
							userInfo.setOrganId((String) map.get("ORGAN_ID"));
							userInfo.setOrganCode((String) map.get("ORGAN_CODE"));
							userInfo.setOrganName((String) map.get("ORGAN_NAME"));
							userInfo.setOrganType((String) map.get("ORGAN_TYPE"));
							userInfo.setOrganParentId((String) map.get("PARENT_ID"));
							// 用户权限信息
							userInfo.setRoleIds(userDao.getUserRoles((String) map.get("USER_ID")));
							userInfo.setUrls(userDao.getUserAuthorizedUrl((String) map.get("USER_ID")));
							RSSecurityUtils.login(getSession(), userInfo);
							ret = 1;
							logMsg = "登陆成功";
						} else {
							if (StringUtils.isNotEmptyObject(map.get("LAST_DENIED_TIME"))) {
								String lastTime = (String) map.get("LAST_DENIED_TIME");
								try {
									lastTime = TimeStampUtils.stampToDateSimple(Long.parseLong(lastTime));
								} catch (Exception e) {
								}

								String nowDate = StringUtils.getDateByFormat("yyyy-MM-dd");
								Long llastTime = TimeStampUtils.dateToStamp(lastTime);
								Long lnowDate = TimeStampUtils.dateToStamp(nowDate);
								String DENIED_VISITS = "1";
								Map system = userDao.getUserSystem();
								String USER_STATUS = "1";
								String LOCK_TIME = "";
								String EXPIRED_TIME = "";
								String LAST_DENIED_TIME = nowTime;
								if ((llastTime + 86400000) <= lnowDate) {
									// 重置限制次数
									DENIED_VISITS = "1";
									if (null == system) {

									} else if (Integer.parseInt(system.get("DENIED_NUM").toString()) <= 1) {
										USER_STATUS = "-1";
										if ("0".equals(system.get("AUTO_LIFTING").toString())) {
											EXPIRED_TIME = "9999999999999";
										} else {
											EXPIRED_TIME = String.valueOf(Long.parseLong(nowTime)
													+ Long.parseLong(system.get("LOCK_TIME").toString()));
										}
										LOCK_TIME = nowTime;

									}

								} else {
									if (null == system) {

									} else if (Integer.parseInt(system.get("DENIED_NUM").toString()) > 1
											+ Integer.parseInt(map.get("DENIED_VISITS").toString())) {
										// 修改限制次数
										USER_STATUS = "1";
										DENIED_VISITS = String
												.valueOf(1 + Integer.parseInt(map.get("DENIED_VISITS").toString()));

									} else {
										// 锁定
										USER_STATUS = "-1";
										LOCK_TIME = nowTime;
										if ("0".equals(system.get("AUTO_LIFTING").toString())) {
											EXPIRED_TIME = "9999999999999";
										} else {
											EXPIRED_TIME = String.valueOf(Long.parseLong(nowTime)
													+ Long.parseLong(system.get("LOCK_TIME").toString()));
										}

										DENIED_VISITS = String
												.valueOf(1 + Integer.parseInt(map.get("DENIED_VISITS").toString()));

									}

								}

								userDao.updateNum(username, USER_STATUS, LOCK_TIME, EXPIRED_TIME, DENIED_VISITS,
										LAST_DENIED_TIME);
							}

							// 登陆失败
							ret = -2;
							logMsg = "密码错误";
						}

					}
				} else {
					// 没有找到该用户
					ret = -1;
					logMsg = "没有该用户";
				}
			}
		}
		this.getSession().setAttribute("verifyImg", "");
		Map res = new HashMap<>();
		res.put("status", ret);
		res.put("expTime", rexpTime);
		try {
			userDao.insertLog(StringUtils.getIpAddr(request), username, "【" + username + "】" + logMsg,
					request.getServletPath(), request.getServletPath() + "?" + (request.getQueryString()),
					request.getHeader("User-Agent"));
		} catch (Exception e) {
			// TODO: handle exception
		}
		this.print(JsonUtils.convertToString(res));
	}

	public void doLogout() throws IOException {
		RSSecurityUtils.logout(getSession());
		this.print("1");
	}

}
